#!/bin/sh

# 压缩包路径前缀
archivePrefix='https://static0.xesimg.com/dbagent/20210426/'
if [ "$supervisorPath" = "" ]; then
    supervisorPath='/etc/supervisor'
fi

# 自动创建日志文件夹
if [ ! -d '/home/logs/xeslog' ]; then
    mkdir -p /home/logs/xeslog
    # chown -R nobody:nobody /home/logs/xeslog
    echo 'info: automatic create logs path /home/logs/xeslog'
fi

if [ ! -d '/home/www/dbagent' ]; then
    mkdir -p /home/www/dbagent
    # chown -R nobody:nobody /home/logs/xeslog
    echo 'info: automatic create logs path mkdir -p /home/www/dbagent/bin'
fi

cd /tmp
archiveName="dbagent.tar.gz"

if [ "$2" != "" ];then
    downloadName="dbagent-$2.tar.gz"
  else
    downloadName=$archiveName
fi

# 下载
curl -o "$archiveName" "${archivePrefix}${downloadName}?t=`date +%s`"

# 解压
tar -zxvf "$archiveName" -C /home/www/dbagent

# 测试环境用测试环境的配置文件
if [ "$1" = "test" ];then
  cp /home/www/dbagent/configs/config_test.toml /home/www/dbagent/configs/config.toml
fi

# 启动服务
if [ "$daemon" != "" ]; then
    # 使用daemon
    echo 'info: use self-daemon manage process'
    # 无论进程是否存在，都重启
else
    # 默认或者指定使用supervisor管理进程
    echo 'info: use supervisor manage process'
    mv /home/www/dbagent/configs/dbagent.ini "${supervisorPath}"
    supervisorctl update
    # 判断进程是否启动中，不是启动中则重启，启动中则忽略
    if [ `supervisorctl status dbagent | grep STARTING | wc -l` -eq 0 ]; then
        supervisorctl restart dbagent
    fi
fi

echo "done, install successfully"
